package ReflectExercise;

import Exercise2.Student;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Field;

public class ReflectDemo {
    public static void main(String[] args) throws IllegalAccessException, IOException {
        Student s = new Student("小妮子",18);
        Teacher t = new Teacher("Yang",35);
        saveObject(s);
    }
    public static void saveObject(Object obj) throws IllegalAccessException, IOException {
        //获取字节码文件的对象
        Class<?> clazz = obj.getClass();

        //创建IO流
        BufferedWriter bw  = new BufferedWriter(new FileWriter("myreflect\\a.txt"));

        //获取所有的成员变量
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            //获取成员变量的名字
            String name = field.getName();
            //获取obj对象中 成员变量的值
            Object value = field.get(obj);
           bw.write(name+"="+value);
           bw.newLine();     //写一行换一行
        }
        bw.close();
    }
}
